package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.WmMaterialDto;
import com.heima.model.media.pojos.WmMaterial;
import com.heima.model.media.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Author 96558
 * @Date 2021/1/15 17:50
 * @Version 1.0
 **/
@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {


    @Autowired
    FileStorageService fileStorageService;

    @Value("${file.oss.profix}")
    String profix;

    @Value("${file.oss.endpoint}")
    String endpoint;

    @Value("${file.oss.web-site}")
    String webSite;

    /**
     * 上传图片接口
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile multipartFile) {
        //1.参数校验
        if (multipartFile==null||multipartFile.getSize()==0){
            CustException.cust(AppHttpCodeEnum.FILE_UPLOAD_PARAMREQUIRE_ERROR);
        }
        //2.上传oss
        String fileId=null;

        try {
            String filename= UUID.randomUUID().toString().replace("-","");
            String originalFilename=multipartFile.getOriginalFilename();
            String postfix=originalFilename.substring(originalFilename.lastIndexOf("."));
            fileId=fileStorageService.store(profix,filename+postfix,multipartFile.getInputStream());
            log.info("filed:{}",fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl uploadPicture error: {}",e);
            throw new CustomException(AppHttpCodeEnum.FILE_UPLOAD_PARAMREQUIRE_ERROR);
        }
        //3.封装数据并保持到素材中
        WmMaterial wmMaterial =new WmMaterial();
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        wmMaterial.setCreatedTime(new Date());

        //设置文件ID
        wmMaterial.setUrl(fileId);
        //当前线程中获取用户ID
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wmMaterial.setUserId(user.getId());
        save(wmMaterial);
        //前端显示
        wmMaterial.setUrl(webSite+fileId);
        //4.返回结果

        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1.校验参数
        dto.checkParam();
        //2.执行业务查询
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        //收藏
        if (dto.getIsCollected()!=null&&dto.getIsCollected()==1){
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollected());
        }
        //当前登录用户的素材
        WmUser user=WmThreadLocalUtils.getUser();
        if (user==null){
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wrapper.eq(WmMaterial::getId,user.getId());
        //时间倒叙
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage<WmMaterial> pageParam = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> resultPage=page(pageParam,wrapper);

        //处理图片
        List<WmMaterial> wmMaterials=resultPage.getRecords();
        for (WmMaterial wmMaterial : wmMaterials) {
            wmMaterial.setUrl(webSite+wmMaterial.getUrl());
        }
        //3.封装结果
        PageResponseResult pageResult = new PageResponseResult(dto.getPage(), dto.getSize(),
                (int) resultPage.getTotal(), resultPage.getRecords());
        return pageResult;
    }
}
